/*
 * Copyright (c) 2020-2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hal_bsp_sht20.h"
#include "hal_bsp_ssd1306.h"

osSemaphoreId_t sem1;

float temperature = 0, humidity = 0;

void sht20_task1(void)
{
    SSD1306_Init(); // OLED 显示屏初始化
    SSD1306_CLS();

    while (1)
    {
        // 此处若只释放一次信号量，则Thread_Semaphore2和Thread_Semaphore3会交替运行。
        osSemaphoreRelease(sem1);
        osDelay(300); // 延时3秒
    }
}

void sht20_task2(void)
{
    SHT20_Init(); // SHT20初始化
    uint8_t temBuff[20] = {0};
    uint8_t humBuff[20] = {0};
    while (1)
    {
        // 等待sem1信号量
        osSemaphoreAcquire(sem1, osWaitForever);
        SHT20_ReadData(&temperature, &humidity);
        sprintf((char *)temBuff, "Tem = %.2f", temperature);
        sprintf((char *)humBuff, "Hum = %.2f", humidity);
        SSD1306_ShowStr(0, 0, (uint8_t *)temBuff, 16);
        SSD1306_ShowStr(0, 3, (uint8_t *)humBuff, 16);
        osDelay(1); // 延时10ms
    }
}

static void oled_sht(void)
{
    osThreadAttr_t attr;
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 4;

    attr.name = "sht20_task1";
    attr.priority = 25;
    if (osThreadNew((osThreadFunc_t)sht20_task1, NULL, &attr) == NULL)
    {
        printf("Falied to create sht20_task1!\n");
    }
    attr.name = "sht20_task2";
    attr.priority = 25;
    if (osThreadNew((osThreadFunc_t)sht20_task2, NULL, &attr) == NULL)
    {
        printf("Falied to create sht20_task2!\n");
    }

    sem1 = osSemaphoreNew(4, 0, NULL); // 创建信号量初始值为0，最大值为4
    if (sem1 == NULL)
    {
        printf("Falied to create Semaphore1!\n");
    }
}

APP_FEATURE_INIT(oled_sht);